package client

import (
	"npxy-go/pkg/proxy"
	"npxy-go/pkg/tcp"
	"sync"
)

type SessionChannelManager struct {
	*proxy.SessionManager
	idSessionChannel *sync.Map
}

func NewSessionChannelManager() *SessionChannelManager {
	return &SessionChannelManager{
		SessionManager:   proxy.NewSessionManager(),
		idSessionChannel: &sync.Map{},
	}
}

func (s *SessionChannelManager) GetSession(id int32) *tcp.Session {
	if ses := s.SessionManager.GetSession(id); ses != nil {
		return ses
	}

	if ch, ok := s.idSessionChannel.Load(id); ok {
		return <-ch.(chan *tcp.Session)
	}

	return nil
}

func (s *SessionChannelManager) CreateSessionChan(id int32) chan *tcp.Session {
	if ch, ok := s.idSessionChannel.Load(id); ok {
		return ch.(chan *tcp.Session)
	}

	sesCh := make(chan *tcp.Session, 1)
	s.idSessionChannel.Store(id, sesCh)

	return sesCh
}

func (s *SessionChannelManager) GetSessionChan(id int32) chan *tcp.Session {
	if ch, ok := s.idSessionChannel.Load(id); ok {
		return ch.(chan *tcp.Session)
	}

	return nil
}
